package ssq.gamest.webserver;

import java.io.File;

import org.apache.http.protocol.HttpRequestHandler;

import ssq.utils.AutoHelpParser;
import ssq.utils.CmdLineParser.Option;
import ssq.utils.DirUtils;
import ssq.utils.HTTPUtils;
import ssq.utils.LogUtils;

public class HttpWebServer
{
    public static void main(String[] args) throws Exception
    {
        runAndGetServer(args);
    }
    
    public static WebServer runAndGetServer(String[] args) throws Exception
    {
        AutoHelpParser parser = new AutoHelpParser("HttpWebServer");
        Option<Integer> portO = parser.addHelp(parser.addIntegerOption('p', "port"), "Web port to listen to", "8080");
        Option<Integer> wsportO = parser.addHelp(parser.addIntegerOption('P', "wsport"), "websocket port used by server", "44343");
        Option<String> indexO = parser.addHelp(parser.addStringOption('i', "index"), "when run as a web server, costum home page file name", "index.html");
        
            parser.parse(args);
        
        String[] otherArgs = parser.getRemainingArgs();
        
        String index = parser.getOptionValue(indexO, "index.html");
        String docRoot = new File(DirUtils.getWebRoot()).getAbsolutePath();
        int port = parser.getOptionValue(portO, 8080);
        int wsport = parser.getOptionValue(wsportO, 44343);
        
        HttpRequestHandler loginHandler = new LoginHandler(wsport);
        final WebServer server = new WebServer("Gamest-HTTP-Server/1.1", port, wsport);
        server.registerHandler("/*", new FileHandler(docRoot, index))
                .registerHandler("/login*", loginHandler)
                .registerHandler("/signup*", loginHandler)
                .registerHandler("/checkName*", loginHandler)
                .create();
        
        LogUtils.logString("Server is now running at port " + port + ", everyone within the same LAN can access files under specified roots by visiting " + HTTPUtils.getLocalIpAddress(true) + (port == 80 ? "" : (":" + port)) + " on its browser. ", "server", false);
        
        server.start();
        
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                server.stopThread();
            }
        });
        
        return server;
    }
}
